<?php
/**
 * 微信端支付，微信后台通知我服务端处理模块
 */
namespace Pay\Controller;
use Common\Model\EventsModel;
use Common\Model\LogModel;
use Common\Model\OrderModel;
use Common\Model\PointMallModel;
use Think\Controller;
class IndexController extends Controller {
    const LOG_FILE='pay';
    private $values = array();
    public function index(){
        $data = file_get_contents('php://input');
        LogModel::dailyLog(self::LOG_FILE,$data);
        $param=$this->parseXml($data);

        $this->SetReturn_code("SUCCESS");
        $this->SetReturn_msg("OK");

        echo $this->ToXml();

        $orderM=M('o_order',null,DB_MAIN_CFG);
        $result=$orderM->where("outTradeNo like '{$param['out_trade_no']}'")
            ->save(
                array('cashFee'=>$param['cash_fee']/100,
                'payTime'=>time()
                )
        );
        if($result===false){
            return;
        }

        $info=$orderM->where("outTradeNo like '{$param['out_trade_no']}'")->field('objType,id')->find();

        switch ($info['objType']){
            case OBJ_TYPE_ACTIVITY:
                EventsModel::afterPay($info['id'],$info['uid'],$info['objID']);
                break;
            case OBJ_TYPE_POINTMALL:
                PointMallModel::afterPay($info['id'],0,$info['uid'],$info['objID']);
                break;
        }



    }
    private function parseXml($xml){
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }


    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function ToXml()
    {
        if(!is_array($this->values)
            || count($this->values) <= 0)
        {
            LogModel::dailyLog(self::LOG_FILE,'输出数组异常');
            die;
        }

        $xml = "<xml>";
        foreach ($this->values as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }


    /**
     *
     * 设置错误码 FAIL 或者 SUCCESS
     * @param string
     */
    public function SetReturn_code($return_code)
    {
        $this->values['return_code'] = $return_code;
    }
    /**
     *
     * 设置错误信息
     * @param string $return_code
     */
    public function SetReturn_msg($return_msg)
    {
        $this->values['return_msg'] = $return_msg;
    }
}